package com.example.demo.controller.advice;

import cn.hutool.jwt.JWTException;
import com.example.demo.domain.dto.ResultDTO;
import com.example.demo.exception.MyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

//增强控制器处理错误信息
@RestControllerAdvice
public class MyControlAdvice {

    ResultDTO resultDTO = new ResultDTO();
    @ExceptionHandler(MyException.class)
    //捕获自定义异常
    public ResultDTO exceptionHandler(Exception e) {

        resultDTO.setCode(500);
        resultDTO.setSuccess(false);
        resultDTO.setMessage(e.getMessage());
        return resultDTO;
    }

    @ExceptionHandler(cn.hutool.jwt.JWTException.class)
    public ResultDTO exceptionHandler(JWTException e) {
        resultDTO.setCode(500);
        resultDTO.setSuccess(false);
        resultDTO.setMessage(e.getMessage());
        return resultDTO;
    }

    //多种未知异常可以使用try-catch异常
    @ExceptionHandler(java.sql.SQLIntegrityConstraintViolationException.class)
    public ResultDTO exceptionHandler(SQLIntegrityConstraintViolationException e) {
        resultDTO.setCode(501);
        resultDTO.setSuccess(false);
        resultDTO.setMessage(e.getMessage());
        return resultDTO;
    }



}
